$(function(){
  try {
    app.socket = io('http://120.77.57.227:8060');
    app.socket.emit('join',app.sign);
    app.socket.on('reply_join',function(msg){
      // numDom.text(msg.num); // 更新实时在线人数
    });
    app.socket.on('reply_send',function(msg){
      // numDom.text(msg.num); // 更新实时在线人数
      if(msg.identity==1 || msg.identity==2){
        app.list.push(msg);
        var scrollFlag = app.scrollBox.height()-app.scrollHeight-app.speakBox.scrollTop()+59 < 50;
        app.showMsg(app.list);
        if(scrollFlag){
          // app.moveToEnd($(".speakContentBox"), !0);
          $(".speakContentBox").stop().animate({ scrollTop: app.scrollBox.height() }, 5);
        }
      }else {
        // app.commontList = [msg].concat(app.commontList);
        app.commontList.push(msg);
        app.showCommont(app.commontList);
      }
    });
    // socket 发送
    app.sockSend = function(content,type, identity,reply_content){
      if(!reply_content){
        reply_content = "";
      }
      identity = identity===0?0:1; // identity 0为在聊天室发言，1为在主屏发言
      var isShowTime = 0, tempTime = new Date().getTime();
      // 每过一百秒没有新消息的时候，下一条消息显示时间
      if(!app.preMsgTime || app.perMsgTime + 100000<tempTime){
        isShowTime = 1;
      }
      app.preMsgTime = tempTime;
      var u = app.user;
      // message_type  0 普通文本，1 图片， 2 语音， 3 提问， 4 上墙， 5 咨询 直播间没有咨询消息
      app.socket.emit('send',{"key":new Date().getTime()+'_'+u.id,"liveid":u.live_id,"unionid":u.unionid,"openid":u.openid,"uid":u.id,
          "course_id":u.course_id,"sign":u.sign,"nickname":u.nickname,"headimgurl":u.headimgurl, 'second':app.audiosTime,'reply_content':reply_content,
          "content":content,"message_type":type,"identity":identity,"flag":isShowTime,"c_time":app.preMsgTime});
    };
    // type 主讲人 'z' , 普通用户 't'
    app.sockDel = function(sign,key,type){
      app.socket.emit('dele',{"sign":sign,"key":key, 'type':type});
    };
    app.socket.on('reply_dele',function(msg){
      var idx = -1;
      if(msg.type == 't'){
        app.commontList.forEach(function(c,i){
          if(c.key == msg.key){
            idx = i;
          }
        });
        app.commontList.splice(idx, 1);
        app.showCommont(app.commontList);
      }else if(msg.type == 'z') {
        app.list.forEach(function(c,i){
          if(c.key == msg.key){
            idx = i;
          }
        });
        app.list.splice(idx, 1);
        app.showMsg(app.list);
      }
    });
  } catch (e) {
    console.log(e);
  } finally {

  }

  var headBox = $('.qlTopicHeadBox');
  app.initFn = function(){
      $("#audioSpan").html('<audio id="audioPlayer" preload="auto" src=""></audio>');
      app.audioDom = document.getElementById('audioPlayer');


      $(".commentBox").delegate(".commentManage", 'click', function(){
        $(".commentBox .commentManageTab").hide();
        $(this).find('.commentManageTab').toggle();
      });
      $(".commentBox").delegate('.delCommentMsg','click',function(){
        var _this = $(this);
        $(document).popBox({
          boxContent: "确定删除吗？",
          btnType: "both",
          confirmFunction: function() {
            var key = _this.parents('.comment_dd').attr('attr-id');
            if(key && key!==""){
              app.sockDel(app.user.sign,key, 't');
              _this.parents('.comment_dd').remove();
            }
          }
        });
      });
      // 主持人在聊天室发言
      $(".submit").click(function(){
        // message_type  0 普通文本，1 图片， 2 语音， 3 提问， 4 上墙， 5 咨询 直播间没有咨询消息
        var type = $(".btn_ask").hasClass('on')?3:0, inputBox = $(".input-box"),
            word = $.trim(inputBox.val());
        if(word!=''){
          app.sockSend(word,type,0);
          inputBox.val('');
        }
      });
      $("#commentDl").delegate('.btn_wall', 'click', function(){
        app.wallDom = $(this).parents('.comment_dd');
        $(".commentReplyBox").show();
      });
      $(".gene_confirm").click(function(){
        var reply = $(".reply_textarea").val(),
            name = app.wallDom.attr('data-name'),
            content = app.wallDom.attr('data-content'),
            key = app.wallDom.attr('attr-id'),
            type = app.wallDom.attr('data-type')=='3'?3:4;
            // message_type  0 普通文本，1 图片， 2 语音， 3 提问， 4 上墙， 5 咨询 直播间没有咨询消息
        // 上墙 4  提问上墙 3
        app.sockSend(name+":"+content, type, 1, reply);
        app.wallDom.find('.btn_wall').removeClass('btn_wall').addClass('btn_iswalled').text('已上墙');
        $(".commentReplyBox").hide();
        $(".reply_textarea").val('')
        $.getJSON(app.host + '/Lecture/addWallStatus?sign='+app.sign+'&key='+key,function(rst){  });
      });

















      // 发送文字消息
      $(".btnLiveTalk").click(function(){
        var word = $(".speakInput").val();
        // message_type  0 普通文本，1 图片， 2 语音， 3 提问， 4 上墙， 5 咨询 直播间没有咨询消息
        if($.trim(word)==""){
          alertMsg("请输入有效的内容再发送");
        }else {
          app.sockSend($.trim(word),0);
          $(".speakInput").val("")
        }

      });

      $(".tabToLiveIndex").click(function(){
        $(".top_menu").toggle();
      });
      $(".btnCloseTopicTips").click(function(){
        $(".topicTipsDl").hide();
      });
      $('.speakContentBox .scrollContentBox').delegate(".btn_revoke", "click", function(){
        var _this = $(this);
        $(document).popBox({
          boxContent: "确定撤回吗？",
          btnType: "both",
          confirmFunction: function() {
            var key = _this.prev().attr('data-id');
            if(key && key!==""){
              app.sockDel(app.user.sign,key, 'z');
              _this.parents('.left_bubble').remove();
            }
          }
        });
      });
      $('.speakContentBox').delegate(".fixPopImg", "click", function(){
        $(this).remove();
      });
      $('.speakContentBox .scrollContentBox').delegate(".img_bubble", "click", function(){
        var src = $(this).find('img').attr("src");

        $(".speakContentBox").append([
          '<div class="fixPopImg">',
          '  <img src="'+src+'" />',
          '</div>'
        ].join());
        var fixImg = $(".fixPopImg img");
        var pH = fixImg.parent().height(), cH = fixImg.height(), mtVal = (pH - cH) / 2 - 50;
        if(pH-cH < 50){
          mtVal = 0;
        }
        fixImg.css("margin-top", mtVal + 'px').parent();
        // layer.photos({
        //     photos: {
        //       "title": "", //相册标题
        //       "id": 123, //相册id
        //       "start": 0, //初始显示的图片序号，默认0
        //       "data": [{
        //           "alt": "图片名",
        //           "pid": 666, //图片id
        //           "src": src, //原图地址
        //           "thumb": "" //缩略图地址
        //       }]
        //     },
        //     anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
        // });
      });
      // $("#audioPlayer").on('ended', function(){
      //   alert('audio 下载完毕，开始播放');
      //   $(this).play();
      // });
      // app.audioDom = document.getElementById('audioPlayer');
      // if (app.audioDom.readyState == 4) {  // android会走此逻辑
      //     app.playAudioFn();
      // } else {    // iOS走此逻辑
      //     app.audioDom.addEventListener("canplaythrough", function() {
      //         app.playAudioFn();
      //     }, false);
      //     app.audioDom.load();    // 需要主动触发下，不然不会加载
      // }
      app.playAudioFn = function(){
        app.playingDom.removeClass('audioloading').addClass('isPlaying');
        app.nowTotalSec = app.playingDom.find('var').text();
        app.playIntervalId = setInterval(function () {
          app.playSecond++;
          if(app.playSecond-1 < app.nowTotalSec){
            var _w = app.playSecond / app.nowTotalSec * 43.2 + 'px';
            app.playingDom.find(".front-bar").css('width', _w).next().css('left',_w);

            if(app.playSecond == app.nowTotalSec){
              app.playSecond = 0;
              clearInterval(app.playIntervalId);
              app.playSrc = '';
              app.playingDom.removeClass('isPlaying isReading').addClass('isReaded');
            }
          }
        }, 997);
      };
      $(".speakContentBox").delegate('.audio_area','click', function(){
        var _key = $(this).attr('data-key'),ls = localStorage.getItem('isReadedList');
        if(!ls || ls.indexOf(_key)==-1){
          app.nowAudioIdx = $(this).attr('data-idx');
          localStorage.setItem('isReadedList',ls+_key+',');
        }else {
          app.nowAudioIdx = '-1';
        }
        var tmpSrc = app.playSrc;
        app.playSrc = $(this).find(".audio_info").attr('attr-src');

        app.playSecond = 0;
        clearInterval(app.playIntervalId);

        // 判断播放的链接是否与正在播放的链接一致，一致则暂停播放，否则就替换链接然后开始播放。
        if(tmpSrc == app.playSrc){
          app.playSrc = '';
          app.audioDom.pause();
          app.playingDom.removeClass('isPlaying isReading audioloading').addClass('isReaded');
        }else {

          app.audioDom.src = app.playSrc;

          app.audioDom.play();

          if(app.playingDom){
            app.playingDom.removeClass('isPlaying isReading').addClass('isReaded').find(".front-bar").css('width', 0).next().css('left',0);
          }

          app.playingDom = $(this).parents('.recordingMsg');
          app.playingDom.addClass('audioloading isPlaying isReading');

        }
      });

      var tabBox = $('.recording_tab_box');
      var pBody = $('.page-body');

      $('.tabToComment, .backToLive').click(function(){
        $('.page-body').toggleClass('hasTabBottom');
        $('.commentBox').toggleClass('isShow').toggle();
        $('.bottom-comment-box').toggle();
      });

      $('.barrage_tab').click(function(){
        $(".barrage_control").toggleClass('on');
        $('.danmuBox').toggle();
        $(this).toggleClass('icon_enter_2 icon_back_2');
      });

      $('.recType_1').click(function(){
        tabBox.removeClass('changeRecType');
      });
      $('.recType_2').click(function(){
        tabBox.addClass('changeRecType');
      });
      $('.tab_voice').click(function(){
        pBody.addClass('voiceBottom').removeClass('mediaBottom textBottom');
      });
      $('.tab_text').click(function(){
        pBody.addClass('textBottom').removeClass('voiceBottom mediaBottom');
        $(".speakInput").focus();
      });
      app.getWebUploader = function(id, uri, fn){
        function afterFn(){
          var uploader = WebUploader.create({
              // 选完文件后，是否自动上传。
              auto: true,
              // swf文件路径
              swf: 'https://cdn.bootcss.com/webuploader/0.1.1/Uploader.swf',
              // 文件接收服务端。
              server: app.host + uri,
              fileVal: 'img',
              // 选择文件的按钮。可选。
              // 内部根据当前运行是创建，可能是input元素，也可能是flash.
              pick: id,
              // 只允许选择图片文件。
              accept: {
                  title: 'Images',
                  extensions: 'gif,jpg,jpeg,bmp,png',
                  mimeTypes: 'image/*'
              },
              compress:{
                width: 1200,
                height: 1200,
                // 图片质量，只有type为`image/jpeg`的时候才有效。
                quality: 90,
                // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
                allowMagnify: false,
                // 是否允许裁剪。
                crop: false,

                // 是否保留头部meta信息。
                preserveHeaders: true,

                // 如果发现压缩后文件大小比原来还大，则使用原来图片
                // 此属性可能会影响图片自动纠正功能
                noCompressIfLarger: false,

                // 单位字节，如果图片大小小于此值，不会采用压缩。
                compressSize: 5242880
            }
          });
          uploader.on('uploadSuccess', fn);
          // uploader.on( 'fileQueued', function( file ) {
          //   app.selectFileImage(file,id);
          // });

        }
        if(typeof WebUploader==="undefined"){
          app.dynamicLoadingCss('https://cdn.bootcss.com/webuploader/0.1.1/webuploader.css');
          app.dynamicLoadingJs('https://cdn.bootcss.com/webuploader/0.1.1/webuploader.min.js', afterFn);
        }else{
          afterFn();
        }
      }
      $('.tab_media').click(function(){
        pBody.addClass('mediaBottom').removeClass('voiceBottom textBottom');
        app.getWebUploader('#filePicker', '/Tool/uploadImg', function(file, response){
          if(response.error===0){
            // message_type  0 普通文本，1 图片， 2 语音， 3 提问， 4 上墙， 5 咨询 直播间没有咨询消息
            app.sockSend(response.url, 1);
          }else{
            alertMsg(response.errMsg);
          }
        });
      });
      // 删除素材
      $(".ppt-select-list").delegate(".icon_trash", "click", function(){
        var id = $(this).parent().attr('data-id'), _this = $(this);
        $(document).popBox({
          boxContent: "是否确定删除素材？",
          btnType: "both",
          confirmFunction: function() {
            $.getJSON(app.host + '/Manager/materialDel', {'material_id': id}, function(rst){
              if(rst.error==0){
                _this.parents('.webkitBox').remove();
              }else {
                alertMsg(rst.errMsg);
              }
            });
          }
        });
      });
      // 发送素材
      $(".ppt-select-list").delegate(".image-content", "click", function(){
        var url = $(this).attr('data-url');
        // message_type  0 普通文本，1 图片， 2 语音， 3 提问， 4 上墙， 5 咨询 直播间没有咨询消息
        app.sockSend(url,1);
        alertMsg('发布成功');
      });
      $(".ppt-select-list").delegate(".icon_up", "click", function(){
        var id = $(this).parent().attr('data-id'), idx=-1;
        for(var i=0, l=app.materialIds.length;i<l;i++){
          if(app.materialIds[i]==id){
            idx = i;
          }
        }
        var tempId = app.materialIds[idx-1];
        app.materialIds[idx-1] = app.materialIds[idx];
        app.materialIds[idx] = tempId;

        var tempM = app.materialList[idx-1];
        app.materialList[idx-1] = app.materialList[idx];
        app.materialList[idx] = tempM;

        app.sortMaterial();
      });
      $(".ppt-select-list").delegate(".icon_down", "click", function(){
        var id = $(this).parent().attr('data-id')
        for(var i=0, l=app.materialIds.length;i<l;i++){
          if(app.materialIds[i]==id){
            idx = i;
          }
        }
        var tempId = app.materialIds[idx+1];
        app.materialIds[idx+1] = app.materialIds[idx];
        app.materialIds[idx] = tempId;

        var tempM = app.materialList[idx+1];
        app.materialList[idx+1] = app.materialList[idx];
        app.materialList[idx] = tempM;

        app.sortMaterial();
      });
      app.sortMaterial = function(){
        $.ajax({
          url:app.host + '/Littlehelper/materialOrder',
          data:{
            course_id:app.user.course_id,
            orders:app.materialIds.join(",")
          },
          type:"POST",
          dataType:"json",
          success:function(rst){
            if(rst.error==0){
              $(".ppt-select-list").html("");
              app.showMaterial(app.materialList);
            }else {
              alertMsg(rst.errMsg);
            }
          }
        });
        // $.getJSON(app.host + '/Manager/materialList?course_id='+app.user.course_id, function(rst){
        //   app.materialList = rst.list;
        //   app.showMaterial(app.materialList);
        // });
      }
      $('.btn_mLibrary, #ppt-close-btn').click(function(){
        $("#ppt-select-layer").toggleClass('on');
        if(!app.initMaterialUpload){
          app.initMaterialUpload=1;
          app.showMaterial = function(list){
            app.materialIds = [];
            var _h = '';
            for(var i=0, l=list.length; i<l; i++){
              var d = list[i];
              app.materialIds.push(d.id);
              _h += ['<li class="webkitBox">',
                '    <div class="boxFlex">',
                '        <div class="image-content" data-url="'+d.url+'">',
                '            <img src="'+d.url+'" alt="">',
                '        </div>',
                '    </div>',
                '    <div class="handle-content" data-id="'+d.id+'"><span class="up icon_up"></span><span class="down icon_down"></span><i class="delete icon_trash"></i>',
                '    </div>',
                '</li>'].join("");
            }
            $(".ppt-select-list").html(_h);
          }
          $.getJSON(app.host + '/Littlehelper/materialList?course_id='+app.user.course_id, function(rst){
            app.materialList = rst.list;
            app.showMaterial(app.materialList);
          });
          app.getWebUploader('#ppt-add-btn', '/Manager/uploadMaterial?course_id='+app.user.course_id, function(file, response){
            if(response.error===0){
              app.materialList.push({'url':response.url, 'id':response.id});
              app.showMaterial(app.materialList);
            }else{
              alertMsg(response.errMsg);
            }
          });
        }

      });

      $(".controlBox, .cbBg").click(function(){
        $('.caozuo_box').toggleClass('on');
      });
      $(".caozuo_cang").click(function(){
        $(".collecttips").toggle();
      });
      $(".caozuo_intro").find('a').attr('href', '/broad/user/#/course?sign='+app.sign);
      $("#btnAutoPlay").click(function(){
        $(this).toggleClass('swon');
        if($(this).hasClass('swon')){
          app.audioDom.onended = app.nextAudio;
        }else {
          app.audioDom.onended = function(){ };
        }
      });
      // 回到第一页 TODO
      $(document).on("click", ".btnFristMsg", function() {
        $(".speakContentBox").stop().animate({ scrollTop: 0 }, 500);
        app.list = []; // 置空数据重新获取
        app.ajaxGetMsg(); //
        headBox.show(); // 若前面没有消息了，则显示顶部的框
        alertMsg("已回到第一条内容", 1);
      });
      app.moveToEnd = function(d, h) {
          var p = d[0].offsetHeight,
              n = d.find(".scrollContentBox")[0].offsetHeight,
              q = d.scrollTop();
          if(h || 600 > n - q - p){
            d.stop().animate({scrollTop: n + 1E3}, 500);
          }
      };
      // 回到最后一页 TODO
      $(document).on("click", ".btn_new_msg", function() {
        app.moveToEnd($(".speakContentBox"), !0);
        app.list = []; // 置空数据重新获取
        app.ajaxGetMsg('','pre'); //
        headBox.hide(); // 隐藏顶部的框
        setTimeout(function(){ alertMsg("已到达最后一条",1); }, 500);
      });
      $(".btn_new_msg").click();

      // 单击开始录音
      $('#btnStartRec').click(function(){
        app.recording = 'start';
        $('#btnCancelRec, .rTips_1').show();
        $('.recording_click .btn_dd').addClass('startRec');
        app.startRec();
      });
      // 单击结束录音
      $('#btnStopRec').click(function(){
        app.recording = 'stop';
        $('.rTips_1').hide();
        $('.rTips_5').show();
        $('.recording_click .btn_dd').addClass('stopRec').removeClass('startRec');
        clearInterval(app.intervalId);
        app.wxStopRec();
      });
      // 单击发送录音
      $('#btnSentRec').click(function(){
        app.recording = '';
        app.time = 0;
        secDom.text(app.time);
        clearInterval(app.intervalId);
        $('#btnCancelRec, .rTips_5').hide();
        $('.recording_click .btn_dd').removeClass('stopRec');
        tabBox.removeClass('recording');

        app.sendFn();
      });
      // 取消录音或点击录音框之外的区域
      $(document).on("click", "#btnCancelRec, .backContentBox", function() {
        if(app.recording=='start' || app.recording=='stop'){
          $(document).popBox({
            boxContent: "取消当条声音录制？",
            btnType: "both",
            confirmFunction: function() {
              app.cancelRec();
            }
          });
        }else {
          pBody.removeClass('voiceBottom textBottom mediaBottom');
        }
      });

      // 长按录音
      app.touchRecordCancelHeight = document.body.offsetHeight - 312;
      $('#btnRecording').on('touchstart', function(e){
        e.preventDefault();
        $(".rTips_3").show();
        app.startRec();
      }).on('touchend',function(e){
        var _y= e.originalEvent.changedTouches[0].pageY;
        if(_y<app.touchRecordCancelHeight){ // 取消录音
          app.cancelRec();
          $(".rTips_4").hide();
        }else {
          $(".rTips_3").hide();
          if(app.time>0){
            app.stopRec(0, 1);
          }else {
            app.cancelRec();
            alertMsg('录音时间太短');
          }
        }

      }).on('touchmove',function(e){
        var _y= e.originalEvent.targetTouches[0].pageY;
        if(_y<app.touchRecordCancelHeight && $(".rTips_4").is(':hidden')){
          $(".rTips_3").hide();
          $(".rTips_4").show();
        }else if(_y>=app.touchRecordCancelHeight && $(".rTips_3").is(':hidden')){
          $(".rTips_3").show();
          $(".rTips_4").hide();
        }
      });
      // 开始录音
      var secDom = $(".second_dd var");
      app.time = 0; app.audios = 0;
      app.startRec = function(){
        tabBox.addClass('recording');
        if(location.href.indexOf('topic')>0){
          app.intervalId = setInterval(function() {
            if(app.time<60){
              app.time++;
              secDom.text(app.time);
            }else {
              app.stopRec();
            }
          },997);
        }
        wx.startRecord({
          fail:function(msg){
            console.log('startRecord fail');
            console.log(msg);
            // wx.stopRecord();
            alertMsg("录音失败，等待刷新后重试", 3);
            setTimeout(function () {
              location.reload();
            }, 2000);
          }, success:function() {
            app.intervalId = setInterval(function() {
              if(app.time<60){
                app.time++;
                $(".second_dd var").text(app.time);
              }else {
                app.stopRec();
              }
            },997);
          }
        });
        wx.onVoiceRecordEnd({
          complete: function(res) {
            app.audios = res.localId;
            app.audiosTime = 60;
            app.stopRec(1); // 微信自动停止 1
            app.autoStartRec = 1; // 发送后自动开始录音

            app.recording ='';
            app.time = 0;
            secDom.text(0);

            app.sendFn(); // 发送语音
          },
          fail: function(rst){
          }
        });

      };
      app.stopRec = function(noWxStopAndCancel, isSend){
        tabBox.removeClass('recording');
        $('#btnCancelRec, .rTips_1').hide();
        $('.recording_click .btn_dd').removeClass('startRec');
        clearInterval(app.intervalId);
        app.recording = 'stop';
        if(!noWxStopAndCancel){ // // 手动停止录音 0， 非 微信自动停止 1，且非 取消录音 2 的
          app.wxStopRec(isSend);
        }else if(noWxStopAndCancel==2){ // 取消录音 2
          wx.stopRecord();
        }
      };
      // 取消录音 function
      app.cancelRec = function(){
        if(app.recording == 'start'){
          app.stopRec(2);
        }else {
          tabBox.removeClass('recording');
        }
        app.recording = '';
        app.time = 0;
        secDom.text(0);
        $('#btnCancelRec, .rTips_1, .rTips_5').hide();
        $('.recording_click .btn_dd').removeClass('startRec stopRec');
      };
      // 发送语音 （上传语音到微信，获取到serverId，再上传到 php 接口获取到语音 url，再调用 websocket 发送 ）
      app.sendFn = function(){
        wx.uploadVoice({
            localId:app.audios,
            isShowProgressTips:1,
            success: function (res){
                app.serverId = res.serverId;
                $.getJSON(app.host + '/Tool/uploadVoice?media_id='+app.serverId, function(rst){
                  if(rst.error===0){
                    // message_type  0 普通文本，1 图片， 2 语音， 3 提问， 4 上墙， 5 咨询 直播间没有咨询消息
                    app.sockSend(rst.url, 2);
                  }else {
                    alertMsg(rst.errMsg);
                  }
                });
            }
        });
      };
      // 停止录音 （调用jssdk）
      app.wxStopRec = function(isSend){

        wx.stopRecord({
          success: function(res) {
            app.audios = res.localId;
            app.audiosTime = app.time?app.time:1;
            if(isSend){ // 停止后马上发送语音
              app.sendFn();
              // 如果停止后马上发送语音，则将时间重置为 0
              app.recording ='';
              app.time = 0;
              secDom.text(0);
            }
          },
          fail: function(rst) {
              // alert('赶快截图给老师，让老师帮助您解决问题吧~ :  '+JSON.stringify(rst));
              rst._type = 'stopRecord';
              rst.useragent = useragent;
              var log ={
                message: JSON.stringify(rst),
                type:_app.planId,
                resource: location.href
              };
              dispatch({ type: 'sign/errorLog', params:log });
          }
        });
      };

      // 是否提问 TODO
      $(".btn_ask i").click(function(){
        $('.btn_ask').toggleClass('on');
      });
      app.nextAudio = function(){
        if(app.nowAudioIdx>-1){
          var doms = $("#speakBubbles dd");
          for(var i=Number(app.nowAudioIdx)+1, l=doms.length; i<l; i++){
            var dom = $(doms[i]).find('.recordingMsg');
            if(dom.length>0 && !dom.hasClass('isReaded')){
              dom.find(".audio_area").click();
              break;
            }
          }
        }
      };
      app.audioDom.onended = app.nextAudio;
      $("#btnAutoPlay").addClass('swon');
      app.audioDom.addEventListener("canplaythrough", function() {
          app.playAudioFn();
      }, false);
  };

  var numDom = $("#xesOLPeople");
  // 初始化 html
  app.initHTML = function(callBackFn){
    var D = app.info;

    // 更新实时在线人数
    // numDom.text('0');
    $(".mine-exit a").click(function(e){
      e.preventDefault();
      location.href = '/broad/user/#/user';
    });
    $('.live-back-wrap').html([
          '<div class="live-back tabToLiveIndex">',
          '    <img src="'+app.resPath+'/img/topic/liveHead.png" alt=""> <span class="live-name">'+D.live_name+'的直播间&nbsp; </span>',
          '</div>',
          '<ul class="top_menu">',
          '    <li><a href="'+'/broad/user/#/course?sign='+app.sign+'">返回主页</a></li>',
          // '    <li><a href="'+'/broad/user/#/course?sign='+app.sign+'">返回系列课</a></li>',
          '</ul>'].join(""));


    // 异步获取用户聊天信息
    app.ajaxGetCommont = function(key,type){
      $.getJSON(app.host + '/Message/list_t?sign='+app.sign+(key?'&key='+key:'')+(type?'&type='+type:''),function(rst){
        app.ajaxFlag = 1;
        app.commontList = rst.concat(app.commontList);
        app.showCommont(app.commontList);
      });
    }
    // 获取某次讲座讨论区的条数
    $.getJSON(app.host + '/Lecture/getListenCount?sign='+app.sign,function(rst){
      app.commentNum = rst.count;
      $("#commentNum").text(app.commentNum);
    });

    app.commontList = [], app.ajaxFlag = 1;
    app.ajaxGetCommont(0,'pre');
    var commontBox = $('.commentContentBox'), commontScorll = $('.commentContentBox .scrollContentBox');
    var commontHeight = $('.commentContentBox').height();
    commontBox.scroll(function(){
        if(app.ajaxFlag){
          var _this = $(this), scrollTop = _this.scrollTop();
          var boxHeight = commontScorll.height()+95;
          if(boxHeight-scrollTop - app.scrollHeight<10){
            app.ajaxFlag=0;
            app.ajaxGetCommont(app.commontList[0].key,'pre');
      　　}
        }
    });



    // 异步获取主讲人与小助手的信息
    app.ajaxGetMsg = function(key,type){
      $.getJSON(app.host + '/Message/list_z?sign='+app.sign+(key?'&key='+key:'')+(type?'&type='+type:''),function(rst3){
        app.ajaxFlag = 1;
        if(type=='pre'){
          if(rst3.length==0){
            headBox.show(); // 若前面没有消息了，则显示顶部的框
          }else {
            // speakBox.scrollTop(10);
            app.list = rst3.concat(app.list);
          }
        }else{
          app.list = app.list.concat(rst3);
        }
        var beforeH = app.scrollBox.height();
        app.showMsg(app.list);
        if(type=='pre'){
          app.speakBox.scrollTop(app.scrollBox.height() - beforeH);
        }
      });
    }
    app.speakBox = $('.speakContentBox'); app.scrollBox = $('.speakContentBox .scrollContentBox');
    app.scrollHeight = $(document).height();
    if(app.list && app.list.length>0){
      app.speakBox.scroll(function(){
        if(app.ajaxFlag){
        　　var _this = $(this), scrollTop = _this.scrollTop();
            var boxHeight = app.scrollBox.height()+95;
        　　if(boxHeight-scrollTop - app.scrollHeight<10){ // 滚动到底部，加载下一页
              app.ajaxFlag=0;
              var key = app.list[app.list.length-1]?app.list[app.list.length-1].key:'';
              app.ajaxGetMsg(key,'next');
        　　}
            if(scrollTop==0 && headBox.is(":hidden")){ // 滚动到顶部且顶部的框隐藏了（说明数据未加载完）
              app.ajaxFlag=0;
              app.ajaxGetMsg(app.list[0].key,'pre');
            }
        }
      });
    }



    app.showMsg(app.list);
    callBackFn();

  };

  // 显示聊天室的信息
  app.showCommont = function(list){
    var _h = '', _h2 = '', l=list.length;
    for(var i=1; i<l+1; i++){
      var d=list[l-i], temp = '', t2='<i class="btn_wall">上墙</i>', t3='';
      if (d.message_type==3) {
        temp = '<em class="ask_label">问</em>';
      }
      if(d.iswalled){
        t2='<i class="btn_iswalled">已上墙</i>';
      }
      if(d.flag==0){ // 有回复
        t3 = '    <p class="content">'+d.content+'</p>';
      }
      _h += ['<dd class="comment_dd" data-type="'+d.message_type+'" attr-id="'+d.key+'" attr-time="'+d.c_time+'" attr-uid="'+d.uid+'" data-name="'+d.nickname+'" data-content="'+d.content+'">',
            '    <span class="right_info">'+t2+' </span>',
            '    <a class="avatar"><img class="" src="'+d.headimgurl+'"></a>',
            '    <span class="author_name">'+d.nickname+'</span><b class="time">'+app.getTime(d.c_time,1)+'</b>',
            // <a class="shutUpSet">禁言</a></span>
            '    <i class="commentManage">管理<span class="commentManageTab" style="display:none;"><a class="delCommentMsg">删除</a></i>',
            t3,
            '    <p class="content" style="'+(d.flag==0?'color:#aaa;':'')+'">'+temp+(d.flag==0?d.reply_content:d.content)+'</p>',
            '</dd>'].join("");
    }
    $("#commentDl").html(_h);

    for(var i=1; i<4; i++){
      var d = list[l-i]?list[l-i]:0; temp = '';
      // message_type  0 普通文本，1 图片， 2 语音， 3 提问， 4 上墙， 5 咨询 直播间没有咨询消息
      if(d){
        if (d.message_type==3) {
          temp = '<em class="ask_label">问</em>';
        }
        _h2 += ['<dd attr-id="'+d.key+'" attr-time="'+d.c_time+'"><i><img src="'+d.headimgurl+'"></i>',
                '    <p>'+ temp + (d.flag==0?d.reply_content:d.content) +'</p>',
                '</dd>'].join("");
      }

    }
    $('.danmulist').html(_h2);
  }
  // 将消息显示到页面（页面加载时或发送消息成功后调用该方法）
  app.showMsg = function(list) {
    var _h = '';
    for(var i=0, l=list.length; i<l; i++){
      // message_type  0 普通文本，1 图片， 2 语音， 3 提问， 4 上墙， 5 咨询 直播间没有咨询消息
      var _temp = '', playBox='', d = list[i];
      playBox = ['<div class="play-box">',
                '    <div class="'+ 'active' +'" data-id="' + d.key + '"><b class="" style="line-height:inherit"></b><span class="count"></span>',
                '    </div><a class="btn_revoke" href="javascript:;" onmicspeak="false">撤回</a>',
                '</div>',].join("");
      if(d.message_type=='0'){
        _temp = ['<div class="bubble_content  green_bubble">',
              '    <div class="bubble_content_main">',
              '        <p>'+ d.content +'</p>',
              '    </div>',
              playBox,
              '</div>',].join("");
      }else if(d.message_type=='1') {
        _temp = ['<div class="bubble_content">',
                '    <div class="bubble_content_main img_bubble">',
                '        <img src="' + d.content + '">',
                '    </div>',
                playBox,
                '</div>',].join("");
      }else if(d.message_type=='2') {
        var isReaded = localStorage.getItem('isReadedList')?(localStorage.getItem('isReadedList').indexOf(d.key)>-1?' isReaded':''):'';
        _temp = ['<div class="bubble_content recordingMsg recordwid1 green_bubble'+isReaded+'">',
                '    <div class="bubble_content_main audio_area" data-key="'+d.key+'" data-idx="'+i+'">',
                '      <i class="audio_info icon_audio_play" attr-src="'+ d.content +'" data-second=' + d.second + '></i>',
                '      <span class="audio-bar-area"><span class="front-bar"></span><span class="block" data-second="' + d.second + '" data-current="0″"><b></b></span></span>',
                '        <var>' + d.second + '</var>',
                '    </div>',
                playBox,
                '</div>',].join("");
      }else if (d.message_type=='3') {
        _temp = ['<div class="bubble_content  green_bubble">',
                '    <div class="bubble_content_main">',
                '        <p><em class="ask_label">问</em><b>' + d.content + '</b></p>',
                (d.reply_content?'<p><b>回复:</b>' + d.reply_content + '</p>':''),
                '    </div>',
                playBox,
                '</div>'].join("");
      }else if (d.message_type=='4') {
        _temp = ['<div class="bubble_content  green_bubble">',
                '    <div class="bubble_content_main">',
                '        <p><b>' + d.content + '</b></p>',
                d.reply_content?'<p><b>回复:</b>' + d.reply_content + '</p>':'',
                '    </div>',
                playBox,
                '</div>'].join("");
      }
      _h += ['<dd class="left_bubble hasTime" attr-id="270000274511171" data-fileid="undefined" attr-time="1489542899000" attr-createby="120000111494497">',
            '    <div class="speak_time">'+ (d.flag&&d.c_time?app.getTime(d.c_time):'') +'</div>',
            '    <div class="head_portrait">',
            '        <img src="' + d.headimgurl + '">',
            '    </div>',
            '    <div class="speaker_name"><b>'+ (d.identity==1?d.nickname:'') +'</b>'+(d.identity==1?'主持人':'小助手')+'</div>',
            _temp,
            '</dd>'].join("");
    }
    $('#speakBubbles').html(_h);
  };

  app.initHTML(function(){
    // 初始化 html 之后隐藏 loading
    app.initFn();
  });
  app.selectFileImage = function(file,domId) {
    file = document.querySelector(domId+" input");
    file = file.files['0']
    console.log(file);
    // var file = fileObj.files['0'];
    //图片方向角 added by lzk
    var Orientation = null;

    if (file) {
        console.log("正在上传,请稍后...");
        var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式
        if (!rFilter.test(file.type)) {
            //showMyTips("请选择jpeg、png格式的图片", false);
            console.log(file.type);
            return;
        }
        // var URL = URL || webkitURL;
        //获取照片方向角属性，用户旋转控制
        EXIF.getData(file, function() {
          console.log('in exif');
           // alert(EXIF.pretty(this));
            EXIF.getAllTags(this);
            //alert(EXIF.getTag(this, 'Orientation'));
            Orientation = EXIF.getTag(this, 'Orientation');
            console.log(Orientation);
            //return;
        });
        var oReader = new FileReader();
        oReader.onload = function(e) {
          console.log('in onload');
            //var blob = URL.createObjectURL(file);
            //_compress(blob, file, basePath);
            var image = new Image();
            image.src = e.target.result;
            image.onload = function() {
                var expectWidth = this.naturalWidth;
                var expectHeight = this.naturalHeight;

                if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {
                    expectWidth = 800;
                    expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
                } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) {
                    expectHeight = 1200;
                    expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
                }
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                canvas.width = expectWidth;
                canvas.height = expectHeight;
                ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
                var base64 = null;
                //修复ios
                if (navigator.userAgent.match(/iphone/i)) {
                    console.log('iphone');
                    //alert(expectWidth + ',' + expectHeight);
                    //如果方向角不为1，都需要进行旋转 added by lzk
                    if(Orientation != "" && Orientation != 1){
                        switch(Orientation){
                            case 6://需要顺时针（向左）90度旋转
                                alert('需要顺时针（向左）90度旋转');
                                app.rotateImg(this,'left',canvas);
                                break;
                            case 8://需要逆时针（向右）90度旋转
                                alert('需要顺时针（向右）90度旋转');
                                app.rotateImg(this,'right',canvas);
                                break;
                            case 3://需要180度旋转
                                alert('需要180度旋转');
                                app.rotateImg(this,'right',canvas);//转两次
                                app.rotateImg(this,'right',canvas);
                                break;
                        }
                    }

                    /*var mpImg = new MegaPixImage(image);
                    mpImg.render(canvas, {
                        maxWidth: 800,
                        maxHeight: 1200,
                        quality: 0.8,
                        orientation: 8
                    });*/
                    base64 = canvas.toDataURL("image/jpeg", 0.8);
                }else if (navigator.userAgent.match(/Android/i)) {// 修复android
                    var encoder = new JPEGEncoder();
                    base64 = encoder.encode(ctx.getImageData(0, 0, expectWidth, expectHeight), 80);
                }else{
                    //alert(Orientation);
                    if(Orientation != "" && Orientation != 1){
                        //alert('旋转处理');
                        switch(Orientation){
                            case 6://需要顺时针（向左）90度旋转
                                alert('需要顺时针（向左）90度旋转');
                                app.rotateImg(this,'left',canvas);
                                break;
                            case 8://需要逆时针（向右）90度旋转
                                alert('需要顺时针（向右）90度旋转');
                                app.rotateImg(this,'right',canvas);
                                break;
                            case 3://需要180度旋转
                                alert('需要180度旋转');
                                app.rotateImg(this,'right',canvas);//转两次
                                app.rotateImg(this,'right',canvas);
                                break;
                        }
                    }

                    base64 = canvas.toDataURL("image/jpeg", 0.8);
                }
                //uploadImage(base64);
                $(domId).attr("src", base64);
                console.log(base64);
            };
        };
        oReader.readAsDataURL(file);
      }
    }

    //对图片旋转处理 added by lzk
    app.rotateImg = function(img, direction,canvas) {
        //alert(img);
        //最小与最大旋转方向，图片旋转4次后回到原方向
        var min_step = 0;
        var max_step = 3;
        //var img = document.getElementById(pid);
        if (img == null)return;
        //img的高度和宽度不能在img元素隐藏后获取，否则会出错
        var height = img.height;
        var width = img.width;
        //var step = img.getAttribute('step');
        var step = 2;
        if (step == null) {
            step = min_step;
        }
        if (direction == 'right') {
            step++;
            //旋转到原位置，即超过最大值
            step > max_step && (step = min_step);
        } else {
            step--;
            step < min_step && (step = max_step);
        }
        //img.setAttribute('step', step);
        /*var canvas = document.getElementById('pic_' + pid);
        if (canvas == null) {
            img.style.display = 'none';
            canvas = document.createElement('canvas');
            canvas.setAttribute('id', 'pic_' + pid);
            img.parentNode.appendChild(canvas);
        }  */
        //旋转角度以弧度值为参数
        var degree = step * 90 * Math.PI / 180;
        var ctx = canvas.getContext('2d');
        switch (step) {
            case 0:
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0);
                break;
            case 1:
                canvas.width = height;
                canvas.height = width;
                ctx.rotate(degree);
                ctx.drawImage(img, 0, -height);
                break;
            case 2:
                canvas.width = width;
                canvas.height = height;
                ctx.rotate(degree);
                ctx.drawImage(img, -width, -height);
                break;
            case 3:
                canvas.width = height;
                canvas.height = width;
                ctx.rotate(degree);
                ctx.drawImage(img, -width, 0);
                break;
        }
    };
});

    // "Tracy Ngan",
